package crp.extensions.xjtu.storage;

import crp.core.resource.app.ResourceService;
import crp.core.resource.domain.models.TimetableResourceSyncRecordEntity;
import crp.core.resource.domain.sync.TimetableResourceSynchronizer;
import com.qwlabs.cdi.Dispatchable;
import crp.extensions.xjtu.XJTU;
import crp.extensions.xjtu.repositories.XJTUResourceSpaceRepository;

import java.util.Objects;


public class XJTUResourceSynchronizer implements Dispatchable<String>, TimetableResourceSynchronizer {
    private final XJTUStorageEngine storageEngine;
    private final ResourceService resourceService;
    private final XJTUResourceSpaceRepository resourceSpaceRepository;


    public XJTUResourceSynchronizer(XJTUStorageEngine storageEngine,
                                    ResourceService resourceService,
                                    XJTUResourceSpaceRepository resourceSpaceRepository) {
        this.storageEngine = storageEngine;
        this.resourceService = resourceService;
        this.resourceSpaceRepository = resourceSpaceRepository;
    }

    @Override
    public boolean dispatchable(String context) {
        return Objects.equals(XJTU.ENV, context);
    }

    @Override
    public boolean sync(TimetableResourceSyncRecordEntity record) {
        var resourceStorage = loadResourceStorage(record);
        if (resourceStorage.isEmpty()) {
            return false;
        }
        sync2Resource(resourceStorage);
        return true;
    }

    private void sync2Resource(XJTUResourceStorage resourceStorage) {
        var command = resourceStorage.createCommand();
        resourceService.editor().create(command);
    }

    private XJTUResourceStorage loadResourceStorage(TimetableResourceSyncRecordEntity record) {
        return XJTUResourceStorage.builder()
                .timetable(record.getTimetable())
                .resourceSpaceRepository(resourceSpaceRepository)
                .storageService(storageEngine)
                .build();
    }
}
